﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClientManager.Data.Infrastucture
{
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        #region Properties

        private bool _disposed;
        private readonly DbContext _dbContext;
        private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>();

        /// <summary>
        /// DbContext EntityFramework 6
        /// </summary>
        public DbContext DbContext
        {
            get
            {
                return _dbContext;
            }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dbContext">DbContext EntityFramework 5</param>
        public UnitOfWork(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Saves changes
        /// </summary>
        /// <returns>Entidades afectadas</returns>
        public void Commit()
        {
            _dbContext.SaveChanges();
        }

        /// <summary>
        /// Returns a repository
        /// </summary>
        /// <typeparam name="T">Base entity</typeparam>
        /// <returns></returns>
        public IRepository<T> GetRepository<T>() where T : class
        {
            object repositorio;

            _repositories.TryGetValue(typeof(T), out repositorio);

            if (repositorio == null)
            {
                repositorio = new GenericRepository<T>(_dbContext);
                _repositories.Add(typeof(T), repositorio);
            }

            return repositorio as IRepository<T>;
        }

        /// <summary>
        /// Frees resources
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        #region Private Methods

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    _dbContext.Dispose();
                }
            }

            _disposed = true;
        }

        #endregion
    }
}
